package com.lianjie.address.service;

import com.lianjie.address.dao.ChainmakerDao;
import com.lianjie.address.entity.ChainmakerEntity;
import com.lianjie.address.util.LinuxUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class AddressService {
    @Autowired
    private ChainmakerDao chainmakerDao;
    private Integer count = 3000;

    public Boolean generateAddress() {
        List<String> addressList = new ArrayList<>();
        String str1 = "/chainmaker/chainmaker-go/tools/cmc/cmc cert addr --cert-path /chainmaker/chainmaker-cryptogen/bin/crypto-config/wx-org";
        String str2 = ".chainmaker.org/user/client1/client1.sign.crt";
        for (int i = 1001; i <= count; i++) {
            String command = str1 + i + str2;
            String result = LinuxUtil.executeLinuxCmd(command);
            if (result != null) {
                String address = result.substring(11);
                addressList.add(address);
            }
        }
        if (!CollectionUtils.isEmpty(addressList)) {
            this.saveAddress(addressList);
        }
        return Boolean.TRUE;
    }

    public void saveAddress(List<String> addressList) {
        System.out.println(addressList);
        List<ChainmakerEntity> chainmakerEntityList = new ArrayList<>();
        addressList.forEach(p -> {
            ChainmakerEntity chainmakerEntity = new ChainmakerEntity();
            chainmakerEntity.setAddress(p);
            chainmakerEntity.setUsed(1);
            chainmakerEntityList.add(chainmakerEntity);

        });
        chainmakerDao.saveAll(chainmakerEntityList);
    }
}
